<?php
/**
 * Created by PhpStorm.
 * User: hoter
 * Date: 2016/4/22
 * Time: 17:58
 */

namespace app\modules\admin\controllers;


use app\core\lib\AccessControl;
use app\models\Menu;
use Yii;
use yii\helpers\Url;
use yii\web\Controller;

class AdminBaseController extends Controller
{
//    public function behaviors()
//    {
//        return [
//            'access' => [
//                'class' => AccessControl::className(),
//                'rules' => [
//                    [
//                        'actions' => ['login', 'error', 'signup', 'upload'],
//                        'allow' => true,
//                    ],
//                    [
//                        'actions' => ['index', 'vote', 'change-pass', 'logout'],
//                        'allow' => true,
//                        'roles' => ['@'],
//                    ],
//                ],
//            ]
//        ];
//    }



    public function init() {
        $this->layout = "main";
    }

    public $menu = [];

    public function beforeAction($action)
    {
        $this->menu = $this->getMenus();
        return parent::beforeAction($action);
    }

    /**
     * 标记当前位置 提供后续跳转
     */
    public function setForward(){
        Yii::$app->getSession()->setFlash('__forward__', $_SERVER['REQUEST_URI']);
    }

    /**
     * 获取之前标记的位置
     */
    public function getForward($default=''){
        $default = $default ? $default : Url::toRoute([Yii::$app->controller->id.'/index']);
        if (Yii::$app->getSession()->hasFlash('__forward__')) {
            return Yii::$app->getSession()->getFlash('__forward__');
        } else {
            return $default;
        }
    }

    /**
     * 操作成功
     * @param string $message
     * @param string $jumpUrl
     * @param bool $ajax
     */
    protected function success($message='', $jumpUrl='', $ajax=false){
        $this->dispatchJump($message, 1, $jumpUrl, $ajax);
    }

    /**
     * 操作失败
     * @param string $message
     * @param string $jumpUrl
     * @param bool $ajax
     */
    protected function error($message='',$jumpUrl='',$ajax=false){
        $this->dispatchJump($message, 0, $jumpUrl, $ajax);
    }

    /**
     * 页面跳转 AJAX返回JSON 正常时返回操作提示页面
     * @param $message
     * @param int $state
     * @param string $jumpUrl
     * @param bool $ajax
     */
    private function dispatchJump($message, $state=1, $jumpUrl='', $ajax=false){
        $jumpUrl = !empty($jumpUrl) ? (is_array($jumpUrl) ? Url::toRoute($jumpUrl) : $jumpUrl) : '';
        //AJAX 提交
        if (true === $ajax || \Yii::$app->request->isAjax) {
            $data = is_array($ajax)?$ajax:[];
            $data['msg'] = $message;
            $data['state'] = $state;
            $data['url'] = $jumpUrl;
            $this->ajaxReturn($data);
        }
        //替他提交信息处理
        $waitSecond = 3;
        // 操作成功
        if ($state) {
            $message = $message ? $message : '操作成功';
            echo $this->renderFile(Yii::$app->params['action_success'],[
                'msg' => $message,
                'waitSecond' => $waitSecond,
                'jumpUrl' => $jumpUrl
            ]);
        } else {
            $message = $message ? $message : '操作失败';
            echo $this->renderFile(Yii::$app->params['action_error'],[
                'msg' => $message,
                'waitSecond' => $waitSecond,
                'jumpUrl' => $jumpUrl
            ]);
        }
    }

    /**
     *  返回JSON数据格式到客户端 包含状态信息
     * @param $data
     * @return mixed
     */
    protected function ajaxReturn($data) {
        header('Content-Type:application/json; charset=utf-8');
        echo json_encode($data);
        exit;
//        Yii::$app->response->format = Response::FORMAT_JSON;
//        return $data;
    }

    final public function getMenus(){
        $menus = (new \yii\db\Query())->from(Menu::tableName())
            ->where(['hide'=>0])
            ->orderBy(['sort'=> SORT_DESC ])
            ->all();
        $controller = $this->id;
        foreach ($menus as $k => $item) {
            if (strpos($item['url'], $controller) !== false) {
                $menus[$k]['class'] = 'active';
            }
        }
        return $menus;
    }

    /**
     * 由表主键删除数据表中的多条记录
     * @param $model
     * @param string $pk
     * @return bool
     */
    public function delRow($model, $pk='id'){
        //$ids = Yii::$app->request->getQueryParam($pk,0);
        $ids = Yii::$app->request->post($pk,0);
        $ids = implode(',', array_unique((array)$ids));
        if (empty($ids)){
            return false;
        }
        $_where = $pk . ' in ('.$ids.')';
        if ($model::deleteAll($_where)) {
            return true;
        }
        return false;
    }
}